package com.example.server.aspect;

import com.example.server.annotation.HaeTransaction;
import com.example.server.connection.HaeConnection;
import com.example.server.trasaction.HaeTransactionManager;
import com.example.server.trasaction.HaeTransactionModel;
import com.example.server.trasaction.TransactionType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.sql.Connection;

/**
 * @Auther: yuanjianpeng
 * @Date: 2019/4/29 10:56
 * @Description:
 */
@Aspect
@Component
public class HaeTransactionAspect implements Order {

    @Around("@annotation(com.example.server.annotation.HaeTransaction)")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        HaeTransaction haeTransaction = method.getAnnotation(HaeTransaction.class);

        //不管从哪个子系统发起的的请求，只要groupId一样，到TX就认为是一个事务组
        String groupId = "";
        if (haeTransaction.isStart()) { //没有就创建
            groupId = HaeTransactionManager.createHaeTransactionGroup();
        } else { //否则从threadLocal里获取
            groupId = HaeTransactionManager.getCurrentGroupId();
        }

        //保证同一线程创建的后面的事务都使用的同一groupId
        HaeTransactionModel haeTransactionModel = HaeTransactionManager.createHaeTransaction(groupId);

        //根据业务执行是否发生异常决定是否提交事务，该操作要么提交要么回滚
        try {
            //调用实际业务逻辑
            joinPoint.proceed();
            //创建成功，正常提交
            HaeTransactionManager.addHaeTransactionModel(haeTransactionModel,haeTransaction.isEnd(), TransactionType.commit);
        } catch (Throwable throwable) {
            //创建异常，需要回滚
            HaeTransactionManager.addHaeTransactionModel(haeTransactionModel,haeTransaction.isEnd(), TransactionType.rollback);
            throwable.printStackTrace();
        }
    }

    @Override
    public int value() { //为了不破坏spring切面的顺序，将优先级定的大一些
        return 9999;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
